import json

from flask import request
from flask_restful import Resource

from App.apis.collection.utils import IbeaconData, get_user
from App.ext import db, redis, mongo
from App.models.bluetooth_gateway_model import UserCollectionIbeacon
from App.models.collection_model import ScannerDate


# 设置扫描参数
class SetScannerParams(Resource):
    def post(self):
        data = request.form
        print(data)
        if data.get("is_collection", None) == "true":
            redis.set("is_collection", 1)
            redis.set("new_line", data.get("distance", 0))
            redis.set("current_mac", data.get("current_mac", ""))
        else:
            redis.set("is_collection", 0)
        return {"code": 0}


# 更新设备
class UpdateScannerParams(Resource):
    def post(self):
        data = request.form
        redis.set("new_line", data.get("distance", 0))
        redis.set("current_mac", data.get("current_mac", ""))

        return {"code": 0}


# 更换收集方式
class SelectCollectionMethod(Resource):
    def post(self):
        data = request.form
        print(data.get("collection_method", "any"))

        redis.set("collection_method", data.get("collection_method", "any"))
        return {"code": 0}


# 收集信标数据
class CollectionResource(Resource):
    """
    原始数据或者(ajax)请求发送的数据
    """

    def post(self):

        if request.is_json:
            data = request.json
            ibeacon = IbeaconData(data, is_raw=False)
        else:
            data = request.data
            ibeacon = IbeaconData(data)
        print(data)

        try:
            parse_data = ibeacon.getData()  # 获取数据 转换后的数据[{"mac":"","rssi":-58,"UUID":"d"},{}]
            db.session.add_all(ScannerDate(**item) for item in parse_data)
            db.session.commit()

            mac_rssis = ibeacon.filterMacRssi(parse_data)

            # 当前存在 mac 写在 redis ["mac1", "mac2", "mac3" ...] 以便前端控制台显示\
            redis.set("macs", json.dumps(list(mac_rssis.keys())))
            print("当前扫描的mac地址", redis.get("macs"))

            # 如果 reids 某个字段开启就收集数据
            if redis.get("is_collection") != "0":
                ibeacon.saveToMongoDB(redis.get("current_mac"))
            return {"code": 201, "msg": "success", "point": "暂无开放"}
        except Exception as e:
            print(e)
            return {"code": 501, "msg": "error"}

        # 如果某个字段关闭 就结束数据


# 微信收集数据
class WechatCollectionResource(Resource):
    """
    微信小程序\web页面\app发送来的蓝牙信标数据
    数据格式:
        {"from": "wechat",
         "by": "用户标识",
         "data": [{"uuid":121312, "major": 01005, "minor": 9, "rssi": -71},{...},...]}
    """

    def post(self):
        data = request.json  # 获取请求的数据
        terminal = data.get("terminal")

        #### 异步提交  ####
        # 保存 data 到 mongodb
        mongo.db.userIbeacon.insert_one(data)
        # 保存数据到mysql
        user = get_user(data.get("by"))
        # 提交信标数据
        db.session.add_all(
            UserCollectionIbeacon(user_id=user.id, terminal=terminal, **item) for item in data.get("data"))
        db.session.commit()

        # 计算用户位置

        # 返回数据
        return {"code": 201, "msg": "success", "point": "一个坐标"}
